//
//  JigSawImageButtonView.m
//  JigSawKiosk
//
//  Created by Stulberg on 10-10-20.
//  Copyright 2010 FruitonLabs. All rights reserved.
//

#import "JigSawImageButtonView.h"

@interface JigSawImageButtonView (Internal)
-(CGImageRef)CGImageNamed:(NSURL*)name;
@end

@implementation JigSawImageButtonView

@synthesize imageLayer, rootLayer, imageName ;


#pragma mark Intialization
- (id)initWithImage:(NSRect)frame name:(NSURL*)name {
    self = [super initWithFrame:frame];
    if (self) {
		imageName = name ;
        [self setupLayers] ;
    }
    return self;
}

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
		[self setupLayers] ;
    }
    return self;
}


#pragma mark setup
-(void) setupLayers {
	rootLayer = [CALayer layer] ;
	rootLayer.backgroundColor = CGColorGetConstantColor(kCGColorWhite) ;
	rootLayer.bounds = CGRectMake(0, 0, [self bounds].size.width, [self bounds].size.height) ;
	[self setLayer:rootLayer] ;
	
	
	CGImageRef image = [self CGImageNamed:imageName] ; // get an image ref
	imageLayer = [CALayer layer] ;
	imageLayer.contents = (id) image ; // make simple layer this image
	imageLayer.frame = [rootLayer bounds] ;
	// Add layers to root	
	[rootLayer addSublayer:imageLayer] ;
	
}

- (void) setImage:(NSURL*)name {
	CGImageRef image = [self CGImageNamed:name] ; // get an image ref
	[CATransaction begin];
	[CATransaction setValue:[NSNumber numberWithFloat: 0.4] forKey:
	 kCATransactionAnimationDuration];
	[CATransaction setValue:[NSNumber numberWithBool: NO] forKey:
	 kCATransactionDisableActions];
	
	imageLayer.contents = (id) image ;	
	
	[CATransaction commit];
}


#pragma mark Image utility
//Return a CGImageRef from the specified image file in the app's bundle
-(CGImageRef)CGImageNamed:(NSURL*)name {
	CFURLRef url = (CFURLRef) name;//[[NSBundle mainBundle] URLForResource:@"miljo.png" withExtension:nil];
	CGImageSourceRef source = CGImageSourceCreateWithURL(url, NULL);
	CGImageRef image = CGImageSourceCreateImageAtIndex(source, 0, NULL);
	CFRelease(source);
	return (CGImageRef)[NSMakeCollectable(image) autorelease];
}


#pragma mark cleanup
- (void) dealloc {
	[rootLayer release] ;
	[imageLayer release] ;
	[imageName release] ;
	[super dealloc] ;	
}

@end
